package com.ht.shop.controller;

import com.alibaba.druid.util.StringUtils;
import com.ht.shop.utils.RequestMappingUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet("/")
public class MyBaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            String uri = req.getRequestURI();//获取实际的请求地址
            System.out.println(uri);
            String methodName = RequestMappingUtils.getMethod(uri);

            String className = methodName.substring(0, methodName.lastIndexOf("."));
            Class<?> targetClass = Class.forName(className);

            Object target = RequestMappingUtils.getTarget(uri);
            if (target == null) {
                target = targetClass.newInstance();
                System.out.println("第一次请求，没有对象，创建对象");
                RequestMappingUtils.addTarget(uri,target);
            }
            Method targetMethod = targetClass.getMethod(methodName.substring(methodName.lastIndexOf("." )+1), HttpServletRequest.class, HttpServletResponse.class);
            String process = (String) targetMethod.invoke(target, req, resp);

            if (!StringUtils.isEmpty(process)) {
                if (process.startsWith("forward:")) {
                    req.getRequestDispatcher(process.replace("forward:","")).forward(req,resp);

                }else if (process.startsWith("redirect:")) {
                    resp.sendRedirect(process.replace("redirect:",""));
                }else {
                    resp.getWriter().write(process);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(404);
        }

    }
}
